package com.lxw.rest.service;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

public class HelloRestTemplateService {
    private static final RestTemplate restTemplate = new RestTemplate();

    static {
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    public Object exchange(String url, HttpMethod method) {
        return exchange(url, method, null, null);
    }

    public Object exchange(String url, HttpMethod method, Object body) {
        return exchange(url, method, body, null);
    }

    public Object exchange(String url, HttpMethod method, Object body, MultiValueMap<String, String> headers) {
        HttpHeaders tempHeaders = new HttpHeaders();
        if (headers != null) {
            tempHeaders.putAll(headers);
        }
        return exchange(url, method, body, tempHeaders);
    }

    public Object exchange(String url, HttpMethod method, Object body, HttpHeaders headers) {
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, entity, String.class);
        HttpStatus statusCode = exchange.getStatusCode();
        if (HttpStatus.OK.equals(statusCode)) {
            return exchange.getBody();
        } else {
            System.out.println("请求失败:" + url);
            System.out.println(exchange);
        }
        return null;
    }
}
